<template>
  <div class="live-code-group-container" v-loading="isAjaxing">
    <el-card class="live-code-header-card">
      <div>
        <h3 class="live-code-header-title">
          <el-link @click.prevent="$router.push('/user-center/live-code/manage')">活码管理</el-link> / <span class="qrcode-manage">二维码管理</span>
        </h3>
        <div class="live-code-column">
          <div class="live-code-column-header">
            <h3>{{ parentsData.name }}</h3>
            <img src="/img/table-operate-images/curve_icon.png" alt="curve_icon" @click="statisticsData.showStatisticsDialog=true;statisticsData.shortData.name =parentsData.name;statisticsData.shortData.short_url=`${parentsData.domain_name}/${parentsData.url}`">
          </div>
          <div class="live-code-column-content">
            <div class="live-code-column-create-time">{{ parentsData.create_time }}</div>
            <div class="live-code-column-link">应用链接：{{ `${parentsData.domain_name}/${parentsData.url}` }}</div>
            <div class="live-code-column-img">
              <img :src="imgRootSrc+'qrcode_icon.png'" alt="qrcode_icon" @click="showDownload">
              <img :src="imgRootSrc+'copy_icon.png'" alt="copy_icon" @click="copyUrl(`${parentsData.domain_name}/${parentsData.url}`)">
            </div>
          </div>
        </div>
        <el-table :data="liveCodeTableData" :border="false">
          <el-table-column type="selection">
          </el-table-column>
          <el-table-column prop="order" label="优先级">
          </el-table-column>
          <el-table-column prop="name" label="群名称">
          </el-table-column>
          <el-table-column prop="code" label="二维码缩略图" min-width="100">
            <template #default="{ row }">
              <img :src="'http://api.frontend.1tz.cn/' + row.code" style="width: 80px;height: 80px;">
            </template>
          </el-table-column>
          <el-table-column prop="invalid_time" label="失效时间">
            <template #default="{ row }">
              <span>{{ row.invalid_time ? row.invalid_time : '永久' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="limit" label="访问上限">
          </el-table-column>
          <el-table-column prop="num" label="累计扫码">
          </el-table-column>
          <el-table-column fixed="right" label="操作">
            <template #default="{ row }">
              <div class="operate-btn">
                <img src="/img/table-operate-images/edit_icon.png" alt="edit_icon" @click="editCodeDialogShow=true;editForm={...row}">
                <img src="/img/table-operate-images/delete_icon.png" alt="delete_icon" @click="deleteCodeFun([row.id])">
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.page"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination >
        <div class="add-qr-code-box" @click="createdialogShow=true;">
          <i class="el-icon-plus"></i>添加二维码
        </div>
        <div class="live-code-footer">
          <div class="live-code-tips">注：最多只能添加200个二维码</div>
          <div class="live-code-btn">
            <el-radio-group v-model="parentsData.rule" size="small">
              <el-radio-button :label="1">顺序切换二维码</el-radio-button>
              <el-radio-button :label="2">随机切换二维码</el-radio-button>
              <el-radio-button :label="3">轮询切换二维码</el-radio-button>
            </el-radio-group>
            <el-checkbox v-model="parentsData.locking" :true-label="1" :false-label="0">用户定位</el-checkbox>
          </div>
          <el-button class="live-code-submit" type="primary" @click="saveConfig">确定</el-button>
        </div>
      </div>
    </el-card>
    <el-dialog v-model="createdialogShow" title="添加二维码" :before-close="(done)=>{isSubmit ? $message.warning('暂时无法关闭') : done()}">
      <el-upload
        :action="baseUrl+'/upload'"
        :headers="uploadHeader"
        :limit="10"
        :data="{path:'code'}"
        :file-list="fileList"
        list-type="picture-card"
        :on-success="uploadSuccess"
        class="avatar-uploader-list">
        <template #default>
          <i class="el-icon-plus"></i>
        </template>
        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">
                <span
                  class="el-upload-list__item-delete"
                  @click="handleRemove(file)"
                >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <el-button @click="createdialogShow = false" type="default" size="mini">取消</el-button>
        <el-button @click="createSubmit" :loading="isSubmit" type="primary" size="mini">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog custom-class="edit-dialog" v-model="editCodeDialogShow" title="修改二维码" :before-close="(done)=>{isSubmit ? $message.warning('暂时无法关闭') : done()}">
      <el-form label-position="top" :model="editForm">
        <div class="edit-dialog-header">
          <div class="edit-header-left">
            <img class="qrcode" :src="baseUrl +'/' + editForm.code" />
          </div>
          <div class="edit-header-right">
            <el-form-item prop="name">
              <template #label>
                <strong>上传二维码图片</strong>
              </template>
              <el-upload
                :action="baseUrl+'/upload'"
                :headers="uploadHeader"
                :data="{path:'code'}"
                :on-success="editUploadSuccess"
                :show-file-list="false"
              >
                <div class="upload_slot">
                  <i class="el-icon-upload2"></i>
                  <span>上传二维码</span>
                </div>
              </el-upload>
              <p class="small_text">注：您可以重新上传二维码替代之前的二维码</p>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="二维码名称">
          <el-input placeholder="请输入二维码名称" v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="访问人数上限">
          <el-input-number
            v-model="editForm.limit"
            controls-position="right"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="展示优先级">
          <el-input-number
            v-model="editForm.order"
            controls-position="right"
            :min="1"
            :max="200"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="失效时间">
          <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="editForm.invalid_time"
            type="datetime" placeholder="选择日期时间"
          ></el-date-picker>
          <p class="small_text">注：失效时间不填则视为永不过期</p>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="default" size="small" @click="editCodeDialogShow = false">取消</el-button>
        <el-button type="primary" size="small" @click="editSubmit" :loading="isSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
  <DataStatistics ref="dataStatisticsRef" v-if="statisticsData.showStatisticsDialog" :statisticsData="statisticsData"></DataStatistics>
</template>

<script>
import { reactive, getCurrentInstance, toRefs, createVNode } from 'vue'
import { useRoute } from 'vue-router'
import { addCode, deleteCode, getCodeList, updateCode, updateliveCode } from '../../../axios/userRequest'
import { computedPage, copySome, downloadSome } from '../../../utils/utils'
import baseUrl from '../../../axios/baseUrl'
import DataStatistics from '@/components/usersComponents/statistics/dataStatistics'
import liveCodeDownloadCode from '../../../components/usersComponents/liveCode/liveCodeDownloadCode'
export default {
  components:{
    DataStatistics
  },
  setup(){
    const { proxy } = getCurrentInstance()
    const route = useRoute()
    const state = reactive({
      statisticsData:{
        showStatisticsDialog:false,
        type:2,
        shortData:{
          name:'',
          short_url:''
        },// 短链数据
        formData:{// 查询数据
          type: 1,// 短链查询
          code_id: route.params.id,// 短链id
        }
      },
      uploadHeader:{'token':localStorage.getItem('userCenter_token')},
      createdialogShow:false,
      editCodeDialogShow:false,
      isAjaxing:true,
      isSubmit:false,
      query:{
        live_code_id:route.params.id,
        page:1,
        limit:10
      },
      total:0,
      imgRootSrc : '/img/my-short-chain-images/short-chain-management-images/',
      liveCodeTableData:[],
      parentsData:{},
      fileList:[],
      uploadData:[],
      editForm:{}
    })

    const getList = () => {
      state.isAjaxing = true
      getCodeList(state.query).then(res=>{
        if(res.code == 0){
          state.parentsData = res.data.parents
          state.liveCodeTableData = res.data.list.data
          state.total = res.data.list.total
        }else{
          proxy.$message.error(res.msg)
        }
        state.isAjaxing = false
      })
    }
    getList()

    const handleSizeChange = (val) => {
      state.query.limit = val
      state.query.page = 1
      getList()
    }

    const handleCurrentChange = (val) => {
      state.query.page = val
      getList()
    }

    const deleteCodeFun = (id) => {
      proxy.$confirm('删除后二维码将不再作为跳转使用，确认要删除该二维码吗？','删除二维码',{
        closeOnClickModal:false,
        customClass:'commonMessageBox',
        type: 'warning',
      }).then(()=>{
        state.isAjaxing = true
        deleteCode({id}).then(res=>{
          if(res.code == 0){
            state.query.page = computedPage(id.length,state.query.page,state.query.limit,state.total)
            getList()
            proxy.$message.success('删除成功')
          }else{
            proxy.$message.error(res.msg)
            state.isAjaxing = false
          }
        })
      })
    }

    const saveConfig = ()=>{
      state.isAjaxing = true
      updateliveCode({
        id:state.parentsData.id,
        rule:state.parentsData.rule,
        locking:state.parentsData.locking,
      }).then(res=>{
        if(res.code == 0){
          proxy.$message.success('保存成功')
        }else{
          proxy.$message.error(res.nsg)
        }
        state.isAjaxing = false
      })
    }

    const copyUrl = (content)=>{
      copySome(content,()=>{
        proxy.$message.success('复制成功')
      })
    }


    const uploadSuccess = (response, file, fileList) => {
      state.fileList = fileList
      if(response.code == 0){
        state.uploadData.push({ type:1,name:'未命名',code: response.data.path})
      }else{
        let index = state.fileList.findIndex(item=>item.uid == file.uid)
        state.fileList.splice(index,1)
        proxy.$message.error(response.msg)
      }
    }

    const handleRemove = (file)=>{
      let index = state.fileList.findIndex(item=>item.uid == file.uid)
      state.fileList.splice(index,1)
      state.uploadData = state.uploadData.filter(item=>{
        return item.code != file.response.data.path
      })
    }

    const createSubmit = () => {
      state.isSubmit = true
      addCode({
        live_code_id: route.params.id,
        data:state.uploadData,
      }).then(res=>{
        if(res.code == 0){
          state.fileList = []
          state.uploadData = []
          getList()
          state.createdialogShow = false
          proxy.$message.success('添加成功')
        }else{
          proxy.$message.error(res.msg)
        }
        state.isSubmit = false
      })
    }

    const showDownload = ()=>{
      proxy.$confirm(createVNode(liveCodeDownloadCode,{
        codeUrl:baseUrl +'/' + state.parentsData.code,
        url:state.parentsData.domain_name +'/' + state.parentsData.url
      }),'下载二维码',{
        closeOnClickModal:false,
        customClass:'commonMessageBox',
        confirmButtonText:'确认下载'
      }).then(()=>{
        downloadSome(baseUrl +'/' + state.parentsData.code,'asdad.png')
      })
    }

    const editSubmit = ()=>{
      state.isSubmit = true
      updateCode(state.editForm).then(res=>{
        if(res.code == 0){
          proxy.$message.success(res.msg)
          state.editCodeDialogShow = false
          getList()
        }else{
          proxy.$message.error(res.msg)
        }
        state.isSubmit = false
      })
    }

    const editUploadSuccess = (response) => {
      if(response.code == 0){
        state.editForm.code = response.data.path
        proxy.$message.success('上传成功')
      }else{
        proxy.$message.error(response.msg)
      }
    }

    return {
      baseUrl,
      ...toRefs(state),
      handleSizeChange,
      handleCurrentChange,
      deleteCodeFun,
      saveConfig,
      copyUrl,
      uploadSuccess,
      handleRemove,
      createSubmit,
      showDownload,
      editSubmit,
      editUploadSuccess
    }
  }
}

</script>

<style lang="less" scoped>
.live-code-group-container {
  width: 100%;
  height: unset !important;
  .el-card {
    height: 100%;
    border: none;

    &:deep(.el-card__body){
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      box-sizing: border-box;
      .el-table {
        margin-top: 40px;
        .cell{
          .operate-btn{
            img{
              margin-right: 25px;
            }
          }
        }
      }
    }
  }
}
.edit-dialog{
  .el-dialog__body{
    .el-form{
      .small_text{
        font-size: 12px;
        margin: 0;
        color: #78797F;
      }
      .edit-dialog-header{
        display: flex;
        flex: 1;
        //margin-bottom: 32px;
        .edit-header-left{
          width: 120px;
          margin-right: 24px;
          .qrcode{
            width: inherit;
            height: 120px;
            background-color: #C1C4CB;
            margin-bottom: 16px;
          }
          .el-button{
            width: inherit;
          }
        }
        .edit-header-right{
          &:deep(.el-upload){
            display: block;
            .upload_slot{
              width: 100%;
              height: 40px;
              border: 1px dashed #ccc;
              text-align: center;
              color: #78797F;
            }
          }
        }
      }
      .el-input-number{
        width: 100%;
      }
    }
  }
}
</style>
